package org.bigdata.framework.core.task;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import org.bigdata.framework.core.model.ShardingDataSource;
import org.bigdata.framework.core.model.ShardingRepositoryCount;
import org.bigdata.framework.core.protocol.BaseService;
import org.bigdata.framework.core.protocol.PublicService;
import org.bigdata.framework.core.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 分库分表处理-定时器处理
 * 
 * @author anhuifeng
 * 
 */
@Service
public class DataTask {

	@Autowired
	private PublicService publicService;
	@Autowired
	private BaseService baseService;

	/**
	 * 定时更新分库分表数据库表记录总数（数据上千万建议一小时更新一次记录总数，其他情况酌情考虑）
	 */
	public void dbCountExecute() {
		
		System.out.println(">>> dataTask-统计分库分表记录数-任务启动....");
		
		List<ShardingRepositoryCount> srcList = publicService
				.getShardingRepositoryCount();
		for (int i = 0; i < srcList.size(); i++) {
			ShardingRepositoryCount aShardingRepositoryCount = srcList.get(i);
			// 数据源
			ShardingDataSource aShardingDataSource = publicService
					.findShardingDataSource(aShardingRepositoryCount
							.getShardingDataSourceId());
			int dataCount = 0; // 记录数

			String sql = " select count(1) as count from "
					+ aShardingRepositoryCount.getTableName() + " ";

			// 执行sql语句
			Connection conn = null;
			Statement stmt = null;
			ResultSet rs = null;

			try {
				conn = DriverManager.getConnection(
						aShardingDataSource.getDbUrl(),
						aShardingDataSource.getDbUser(),
						aShardingDataSource.getDbPassword());

				stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
						ResultSet.CONCUR_UPDATABLE);
				rs = stmt.executeQuery(sql);
				if (rs.next()) {
					dataCount = rs.getInt(1);
				}

			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				// 关闭
				if (rs != null)
					try {
						rs.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				if (stmt != null)
					try {
						stmt.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				if (conn != null)
					try {
						conn.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				rs = null;
				stmt = null;
				conn = null;
			}

			// 更新表
			aShardingRepositoryCount.setDataCount(dataCount);
			aShardingRepositoryCount.setUpdateTime(DateUtils.getDateTime());
			baseService.editShardingRepositoryCount(aShardingRepositoryCount);
		}
		
		System.out.println(">>> dataTask-统计分库分表记录数-任务结束....");
		
	}

}
